﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using System.Web.Services;
using ProjectSemIII.Administrator.Process;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;

namespace ProjectSemIII.Administrator.Survey
{
    public partial class CreateSurvey : System.Web.UI.Page
    {
        protected string Values;
        private List<Entity.SurveyCatalog> listSurveyCatalog;
        private SurveyProcess surveyProcess;
        private int dateStart;
        private List<string> questionList;
        private List<Entity.Question> listQuestion;
        protected void Page_Load(object sender, EventArgs e)
        {
            surveyProcess = new SurveyProcess();
            questionList = new List<string>();
            listQuestion = new List<Entity.Question>();
            if (Request.QueryString["step"] == "1" || Request.QueryString.Count == 0)
            {
                divSurveyInfo.Visible = true;
                divSurveyDetail.Visible = false;
                if (Session["Result"] != null)
                {
                    lbError.Text = Session["Result"].ToString();
                    this.clearSessionSurvey();
                }
                if (!Page.IsPostBack)
                {
                    this.getAllSurveyCatalog();
                    DateTime today = DateTime.Today;
                    startDate.SelectedDate = today;
                    deadLine.SelectedDate = today.AddDays(1);
                }
            }
            else if (Request.QueryString["step"] == "2")
            {
                divSurveyInfo.Visible = false;
                divSurveyDetail.Visible = true;
                if (Session["Question"] == null || Request.QueryString.Count == 1)
                {
                    Response.Redirect("CreateSurvey.aspx?step=1");
                }
                else
                {
                    if (Convert.ToInt32(Request.QueryString["question"]) > ((List<string>)Session["Question"]).Count)
                    {
                        Response.Redirect("/404.html");
                    }
                    else
                    {
                        if (Convert.ToInt32(Request.QueryString["question"]) == ((List<string>)Session["Question"]).Count)
                        {
                            btNext.Text = "Submit";
                            if (Convert.ToInt32(Session["Catalog"]) == 1)
                            {
                                rbComment.Visible = false;
                            }
                        }
                        else if (Convert.ToInt32(Request.QueryString["question"]) == 1)
                        {
                            btPrev.Text = "Back";
                        }
                        lbQuestionNumber.InnerText = ((List<string>)Session["Question"])[Convert.ToInt32(Request.QueryString["question"]) - 1].ToString();
                        if (rbComment.Checked == true)
                        {
                            answerForm.Visible = false;
                        }
                        else
                        {
                            answerForm.Visible = true;
                        }
                    }
                }
            }
            else
            {
                Response.Redirect("/404.html");
            }
        }

        private void clearSessionSurvey()
        {
            Session["Catalog"] = null;
            Session["SurveyName"] = null;
            Session["SurveyDesc"] = null;
            Session["JoinGroup"] = null;
            Session["StartDate"] = null;
            Session["DeadLine"] = null;
            Session["ImageSurvey"] = null;
            Session["SurveyID"] = null;
            Session["Question"] = null;
            Session["ListQuestion"] = null;
            Session["Result"] = null;
        }

        private void getAllSurveyCatalog()
        {
            listSurveyCatalog = new List<Entity.SurveyCatalog>();
            Entity.SurveyCatalog sc = new Entity.SurveyCatalog();
            sc.CatalogName = "Select Catalog Name";
            sc.CatalogID = -1;
            listSurveyCatalog.Add(sc);
            foreach (Entity.SurveyCatalog esc in surveyProcess.getAllSurveyCatalog())
            {
                listSurveyCatalog.Add(esc);
            }
            SurveyCatalogName.DataSource = listSurveyCatalog;
            SurveyCatalogName.DataTextField = "CatalogName";
            SurveyCatalogName.DataValueField = "CatalogID";
            SurveyCatalogName.DataBind();
        }

        protected void SurveyCatalogName_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddl = (DropDownList)sender;
            nameChoose.InnerText = ddl.SelectedItem.Text;
            if (Convert.ToInt32(ddl.SelectedValue) == 1)
            {
                txtNumberQuestion.Text = "1";
                txtNumberQuestion.Enabled = false;
            }
        }

        protected void ddPlayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddl = (DropDownList)sender;
            idGroup.InnerText = ddl.SelectedItem.Text;
        }

        private bool validateFormStep1()
        {
            bool flag = true;
            int num;
            bool checkInt = int.TryParse(txtNumberQuestion.Text, out num);
            if (ddPlayer.SelectedItem.Value == "-1" || SurveyCatalogName.SelectedItem.Value == "-1")
            {
                if (ddPlayer.SelectedItem.Value == "-1")
                {
                    lbError.Text = "Please select group for survey!";
                    flag = false;
                }
                else
                {
                    lbError.Text = "Please select survey catalog!";
                    flag = false;
                }
            }
            else
            {
                if (txtSurveyName.Text == "" || txtSurveyName.Text == null)
                {
                    lbError.Text = "Please enter survey name!";
                    flag = false;
                }
                else if (txtNumberQuestion.Text == "" || txtNumberQuestion.Text == null)
                {
                    lbError.Text = "Please enter number of question!";
                    flag = false;
                }
                else if (!checkInt)
                {
                    lbError.Text = "Number of the question is a number!";
                    flag = false;
                }
                else if (num == 0 || num > 10)
                {
                    lbError.Text = "Number of the question is not valid!";
                    flag = false;
                }
                else if (txtSurveyDesc.Text == "" || txtSurveyDesc.Text == null)
                {
                    lbError.Text = "Please enter survey description!";
                    flag = false;
                }
                else if (fuImages.HasFile)
                {
                    string fileName = fuImages.PostedFile.FileName;
                    if (Path.GetExtension(fileName) != ".jpg" && Path.GetExtension(fileName) != ".jpeg" && Path.GetExtension(fileName) != ".gif" && Path.GetExtension(fileName) != ".png")
                    {
                        lbError.Text = "The file format is not valid";
                        flag = false;
                    }
                    else if (fuImages.PostedFile.ContentLength > 1048576)
                    {
                        lbError.Text = "File must be less than 1MB.";
                        flag = false;
                    }
                }
            }
            return flag;
        }

        private bool validateQuestion()
        {
            bool flag = true;
            if (txtQuestion.Text == "" || txtQuestion.Text == null)
            {
                lbErrorQuestion.Text = "Please enter question!";
                flag = false;
            }
            else if (rbComment.Checked == false)
            {
                string[] textboxValues = Request.Form.GetValues("DynamicTextBox");
                if (textboxValues == null || textboxValues.Length < 1)
                {
                    lbErrorQuestion.Text = "Please add answers!";
                    flag = false;
                }
                else
                {
                    if (Convert.ToInt32(Session["Catalog"]) == 1)
                    {
                        if (textboxValues.Length <= 3)
                        {
                            lbErrorQuestion.Text = "Vote Student Survey have min 4 student!";
                            flag = false;
                        }
                        foreach (string w in textboxValues)
                        {
                            int n;
                            bool isNumeric = int.TryParse(w, out n);
                            if (w == "" || w == null)
                            {
                                lbErrorQuestion.Text = "Please enter student name!";
                                flag = false;
                            }
                            if (isNumeric)
                            {
                                lbErrorQuestion.Text = "Student name is wrong format!";
                                flag = false;
                            }
                        }
                    }
                    else
                    {
                        foreach (string w in textboxValues)
                        {
                            if (w == "" || w == null)
                            {
                                lbErrorQuestion.Text = "Please enter answers!";
                                flag = false;
                            }
                        }
                    }
                }
            }
            return flag;
        }

        protected void submitStep1_Click(object sender, EventArgs e)
        {
            if (validateFormStep1())
            {
                Session["Catalog"] = SurveyCatalogName.SelectedValue;
                Session["SurveyName"] = txtSurveyName.Text;
                Session["SurveyDesc"] = txtSurveyDesc.Text;
                Session["JoinGroup"] = ddPlayer.SelectedValue;
                Session["StartDate"] = startDate.SelectedDate;
                Session["DeadLine"] = deadLine.SelectedDate;
                if (fuImages.HasFile)
                {
                    try
                    {
                        Session["ImageSurvey"] = fuImages.PostedFile.FileName;
                        fuImages.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/Images/Surveys/" + fuImages.FileName));
                    }
                    catch
                    {
                        Session["ImageSurvey"] = fuImages.PostedFile.FileName;
                    }
                }
                else
                {
                    Session["ImageSurvey"] = "Default.png";
                }
                for (int i = 1; i <= Convert.ToInt32(txtNumberQuestion.Text); i++)
                {
                    questionList.Add("Question Number " + i.ToString());
                }
                if (!surveyProcess.getAllSurvey().Any())
                {
                    Session["SurveyID"] = 1;
                }
                else
                {
                    Session["SurveyID"] = surveyProcess.getAllSurvey().OrderByDescending(s => s.SurveyID).FirstOrDefault().SurveyID + 1;
                }
                Session["Question"] = questionList;
                Response.Redirect("CreateSurvey.aspx?step=2&question=1");
            }
        }

        protected void deadLine_DayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date.CompareTo(DateTime.Today.AddDays(dateStart + 1)) < 0)
            {
                e.Day.IsSelectable = false;
            }
        }

        protected void startDate_DayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date.CompareTo(DateTime.Today) < 0)
            {
                e.Day.IsSelectable = false;
            }
        }

        protected void startDate_SelectionChanged(object sender, EventArgs e)
        {
            deadLine.SelectedDate = startDate.SelectedDate.AddDays(1);
            TimeSpan sp = startDate.SelectedDate.Subtract(DateTime.Now.Date);
            dateStart = sp.Days;
        }

        protected void btNext_Click(object sender, EventArgs e)
        {
            if (Session["ListQuestion"] != null)
            {
                listQuestion = (List<Entity.Question>)Session["ListQuestion"];
            }
            else
            {
                listQuestion = new List<Entity.Question>();
            }
            string[] textboxValues = Request.Form.GetValues("DynamicTextBox");
            Entity.Question question = new Entity.Question();
            question.QuestionDetail = txtQuestion.Text;
            question.SurveyID = Convert.ToInt32(Session["SurveyID"]);
            int questionType = 0;
            if (rbRadio.Checked)
            {
                questionType = 1;
                foreach (string w in textboxValues)
                {
                    if (w == textboxValues[0])
                    {
                        question.Answers += w;
                    }
                    else
                    {
                        question.Answers += "#" + w;
                    }
                }
            }
            else if (rbComment.Checked)
            {
                questionType = 2;
                question.Answers = "";
            }
            else
            {
                questionType = 3;
                foreach (string w in textboxValues)
                {
                    if (w == textboxValues[0])
                    {
                        question.Answers += w;
                    }
                    else
                    {
                        question.Answers += "#" + w;
                    }
                }
            }
            question.QuestionTypeID = questionType;
            listQuestion.Add(question);
            if (btNext.Text == "Next Question")
            {
                if (this.validateQuestion())
                {
                    Session["ListQuestion"] = listQuestion;
                    Response.Redirect("CreateSurvey.aspx?step=2&question=" + (Convert.ToInt32(Request.QueryString["question"]) + 1));
                }
            }
            else if (btNext.Text == "Submit")
            {
                Entity.Survey sv = new Entity.Survey();
                sv.SurveyName = Session["SurveyName"].ToString();
                sv.SurveyDesc = Session["SurveyDesc"].ToString();
                sv.SurveyImage = Session["ImageSurvey"].ToString();
                sv.SurveyPlayer = Convert.ToInt32(Session["JoinGroup"]);
                sv.SurveyStartDate = Convert.ToDateTime(Session["StartDate"]);
                if (Convert.ToDateTime(Session["StartDate"]) == DateTime.Today)
                {
                    sv.SurveyStatus = 1;
                }
                else
                {
                    sv.SurveyStatus = 2;
                }
                sv.SurveyDateLine = Convert.ToDateTime(Session["DeadLine"]);
                sv.CatalogID = Convert.ToInt32(Session["Catalog"]);
                int resultInsertSurvey = surveyProcess.createNewSurvey(sv);
                if (resultInsertSurvey == 10)
                {
                    int resultInsertQuestion = surveyProcess.insertQuestionToSurvey(listQuestion);
                    if (resultInsertQuestion == 10)
                    {
                        Session["Result"] = "Create new survey successful!";
                        Response.Redirect("CreateSurvey.aspx?step=1");
                    }
                    else
                    {
                        Session["Result"] = "Error in insert question to survey!";
                        Response.Redirect("CreateSurvey.aspx?step=1");
                    }
                }
                else
                {
                    Session["Result"] = "Error in create new survey!";
                    Response.Redirect("CreateSurvey.aspx?step=1");
                }
            }
        }
    }
}